package com.soujiayi.coupon;

import java.util.Random;
import java.util.TreeSet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;


public class Utils {
	public static final int SRC = 0x0;
	public static final int BG = 0x1;

	public static final int TAB_HOME_SHOW = 0xab01;
	public static final int TAB_DETAIL_SHOW = 0xab02;
	public static final int TAB_TITLE_CLASSI = 0xab03;
	public static final int TAB_TITLE_RANK = 0xab04;
	public static final int TAB_SHOW_DETAIL = 0xab05;
	public static final int ADAPTER_UPDATE = 0xab06;
	public static final int PROGRESSBAR_VISIBLE = 0xab07;
	public static final int PROGRESSBAR_GONE = 0xab08;
	public static final int LISTVIEW = 0xab09;
	public static final int PARSE_DATA = 0xab10;
	public static final int MAIN_HANDLER_UPDATE = 0xab11;
	public static final int FOOTVIEW_GONE = 0xab12;
	public static final int ALERT = 0xab13;
	public static final int FOOTVIEW_REMOVE = 0xab14;
	public static final int PARSE_GALLERY_DATA = 0xab15;
	public static final int COLLECTION = 0xab16;
	public static final int RESULT = 0xab17;
	public static final int RESULT_CODE = 0xab18;
	public static final int DELETE = 0xab19;
	public static final int DOWNLOAD = 0xab20;
	public static final int UPDATE = 0xab21;
	public static final int TAGADD = 0xab22;
	public static final int PROGRESS_DIALOG_VISIBLE = 0xab23;
	public static final int PROGRESS_DIALOG_GONE = 0xab24;
	public static final int PARSE_ZT_IN_DATA = 0xab25;
	public static final int FOOTVIEW_GONE2 = 0xab26;
	public static final int FOOTVIEW_REMOVE2 = 0xab27;
	public static final int PARSE_TAG_DATA = 0xab28;
	public static final int PARSE_SHOP_DATA = 0xab29;
	public static final int STORE = 0xab30;
	public static final int SET_LV_HEIGHT = 0xab31;
	public static final int SHOW_PD = 0xab32;

	public static final int notification_id = 19172439;
	public static int PAGESIZE = 5;



	// 验证网络
	public static boolean hasInternet(Activity activity) {
		Context context = activity.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

//	// 隐藏软键盘
//	public static void hiddenKeyboard(Activity activity) {
//		((InputMethodManager) activity
//				.getSystemService(HomepageActivity.INPUT_METHOD_SERVICE))
//				.hideSoftInputFromWindow(activity.getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//	}

	public static void setupTabHost(Bundle savedInstanceState, Activity a,
			TabHost tabHost) {
		LocalActivityManager activityGroup = new LocalActivityManager(a, false);
		activityGroup.dispatchCreate(savedInstanceState);
		activityGroup.dispatchResume();
		tabHost.setup(activityGroup);
	}

	public static void commonInit(Activity a) {
		//ActivityFactory.add(a);
		setTitleDim(a);
		setNaviDim(a);
	}

	// 设置控件大小
	public static void setlp(View v, int w, int h, int sW, int sH) {
		// if (v instanceof LinearLayout || v instanceof Button
		// || v instanceof EditText) {
		// v.setLayoutParams(new LinearLayout.LayoutParams(sW * w / 64 / 5, sW
		// * h / 64 / 5));
		// }
	}

	public static void setrlp(View v, int w, int h, int sW, int sH) {
		// if (v instanceof LinearLayout || v instanceof Button
		// || v instanceof EditText) {
		// RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
		// sW * w / 64 / 5, sW * h / 64 / 5);
		// rlp.addRule(RelativeLayout.CENTER_VERTICAL);
		// rlp.leftMargin = sW / 64;
		// v.setLayoutParams(rlp);
		// }
	}

	public static void setTitleDim(Activity a) {
		// Point p = ImageUtils.getScreenPoint(a);
		// int sW = p.x;
		// RelativeLayout rl = (RelativeLayout) a.findViewById(R.id.title);
		// RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
		// RelativeLayout.LayoutParams.FILL_PARENT, sW * 44 / 64 / 5);
		// rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		// rl.setLayoutParams(rlp);
	}

	public static void setNaviDim(Activity a) {
		// Point p = ImageUtils.getScreenPoint(a);
		// int sW = p.x;
		// int sH = p.y;
		// LinearLayout ll = (LinearLayout) a.findViewById(R.id.navi);
		// RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
		// RelativeLayout.LayoutParams.FILL_PARENT, sH * 50 / 480);
		// rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		// ll.setLayoutParams(rlp);
	}

	// 获得屏幕高宽
	public static Point getScreenPoint(Activity activity) {
		WindowManager windowManager = activity.getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		Point point = new Point(display.getWidth(), display.getHeight());
		return point;
	}

	public static int getsW(Activity a) {
		return getScreenPoint(a).x;
	}

	public static int getsH(Activity a) {
		return getScreenPoint(a).y;
	}

	public static int getScreenOrientation(Activity a) {
		return a.getResources().getConfiguration().orientation;
	}

	public static String getDisplayMetrics(Context cx) {
		String str = "";
		DisplayMetrics dm = new DisplayMetrics();
		dm = cx.getApplicationContext().getResources().getDisplayMetrics();
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		float density = dm.density;
		float xdpi = dm.xdpi;
		float ydpi = dm.ydpi;
		str += "The absolute width:" + String.valueOf(screenWidth) + "pixels\n";
		str += "The absolute heightin:" + String.valueOf(screenHeight)
				+ "pixels\n";
		str += "The logical density of the display.:" + String.valueOf(density)
				+ "\n";
		str += "X dimension :" + String.valueOf(xdpi) + "pixels per inch\n";
		str += "Y dimension :" + String.valueOf(ydpi) + "pixels per inch\n";
		return str;
	}

	/** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */
	public static int dp2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);

	}

	/** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */
	public static int px2dp(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	// 返回字体
	public static Typeface getFont(Context c) {
		Typeface face = Typeface.createFromAsset(c.getAssets(),
				"fonts/wryh.ttf");
		return face;
	}

	// // 回收内存
	// public static void recycleBitmap(ArrayList<? extends ImageBean>
	// imageBeans) {
	// // Bitmap bitmap;
	// // for (int i = 0; i < imageBeans.size(); i++) {
	// // bitmap = imageBeans.get(i).getBitmap();
	// // if (bitmap != null && !bitmap.isRecycled()) {
	// // bitmap.recycle();
	// // }
	// // }
	// }
	//
	// // 回收内存
	// public static void recycleBitmap(ArrayList<? extends ImageBean>
	// imageBeans,
	// int item) {
	// // Bitmap bitmap;
	// // for (int i = 0; i < item; i++) {
	// // bitmap = imageBeans.get(i).getBitmap();
	// // if (bitmap != null) {
	// // bitmap.recycle();
	// // System.out.println("recycle");
	// // }
	// // }
	// }

	public static TreeSet<String> getUnRepeat(int amount, String strings[]) {
		TreeSet<String> treeSet = new TreeSet<String>();
		Random r = new Random();
		int n = strings.length;
		while (treeSet.size() != amount) {
			treeSet.add(strings[r.nextInt(n)]);
		}
		return treeSet;
	}

	public static void fadeAndTran(View view, int visibility, float startAlpha,
			float endAlpha, float fromXDelta, float toXDelta, float fromYDelta,
			float toYDelta) {
		AnimationSet animationSet = new AnimationSet(true);
		TranslateAnimation translateAnimation = new TranslateAnimation(
				TranslateAnimation.RELATIVE_TO_SELF, fromXDelta,
				TranslateAnimation.RELATIVE_TO_SELF, toXDelta,
				TranslateAnimation.RELATIVE_TO_SELF, fromYDelta,
				TranslateAnimation.RELATIVE_TO_SELF, toYDelta);
		translateAnimation.setDuration(1500);
		AlphaAnimation alphaAnimation = new AlphaAnimation(startAlpha, endAlpha);
		alphaAnimation.setDuration(1500);
		animationSet.addAnimation(translateAnimation);
		animationSet.addAnimation(alphaAnimation);

		animationSet.setStartTime(Animation.START_ON_FIRST_FRAME);
		view.setAnimation(animationSet);
		view.invalidate();
		view.setVisibility(visibility);
	}

	public static void fade(View view, int visibility, float startAlpha,
			float endAlpha) {
		AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
		anim.setDuration(500);
		anim.setStartTime(Animation.START_ON_FIRST_FRAME);
		view.setAnimation(anim);
		view.invalidate();
		view.setVisibility(visibility);
	}

	public static Animation getFadeAnim(float startAlpha, float endAlpha) {
		AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
		anim.setDuration(500);
		anim.setStartTime(Animation.START_ON_FIRST_FRAME);
		return anim;
	}

	// 跳转到详情页面
	// public void toDetail(Context mContext, Class<? extends Activity> mClass,
	// ArrayList<? extends ImageBean> list, int position) {
	// Intent intent = new Intent();
	// intent.setClass(mContext, mClass);
	// Bundle bundle = new Bundle();
	// bundle.putString("apkName", list.get(position).getApkName());
	// bundle.putString("apkUrl", list.get(position).getApkUrl());
	// bundle.putString("imgUrl", list.get(position).getImgUrl());
	// intent.putExtras(bundle);
	// mContext.startActivity(intent);
	// }

	public static View composeLayout(Context c, String tabName, int id, int w,
			int h) {
		RelativeLayout layout = new RelativeLayout(c);
		RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		rlp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		layout.setLayoutParams(rlp);

		ImageView iv = new ImageView(c);

		iv.setBackgroundResource(id);

		layout.addView(iv, new LinearLayout.LayoutParams(w, h));
		// layout.addView(iv, new LinearLayout.LayoutParams(
		// ViewGroup.LayoutParams.WRAP_CONTENT,
		// ViewGroup.LayoutParams.WRAP_CONTENT));

		TextView tv = new TextView(c);
		tv.setSingleLine(true);
		tv.setText(tabName);
		//tv.setTextColor(c.getResources().getColor(R.color.black));

		layout.addView(tv, rlp);
		return layout;
	}

	public static void addFootView(Context c, LinearLayout footView, ListView lv) {
		ProgressBar progressBar = new ProgressBar(c);
		footView.addView(progressBar);

		TextView tv = new TextView(c);
		tv.setText("加载中请稍候……");
		footView.addView(tv);
		lv.addFooterView(footView);
	}

	// public static void showLogin(final Context c) {
	// new AlertDialog.Builder(c)
	// .setTitle("提示")
	// .setMessage("您尚未登录,请先登录")
	// .setPositiveButton("现在登录",
	// new android.content.DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int which) {
	// Intent intent = new Intent();
	// intent.setClass(c, LoginUser.class);
	// ((Activity) c)
	// .startActivityForResult(intent, 0);
	// }
	// })
	// .setNeutralButton("取消",
	// new android.content.DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog,
	// int which) {
	// // do nothing.
	// }
	// }).show();
	// }

	public static void showPd(ProgressDialog pd, String text) {
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setTitle(text);
		pd.show();
	}

	public static void alert(Context c) {
		new AlertDialog.Builder(c).setTitle("提示！").setMessage("连接失败")
				.setPositiveButton("确定", null).show();
	}

	// // 注销
	// public static void logout() {
	// User.getUser().setUsername(null);
	// User.getUser().setUser_id(null);
	// Homepage.staticHandler.sendEmptyMessage(MyDATA.SHOW_BUTTON);
	// }

	// 提示
	public static void resultShow(final Context c, String result,
			String showString) {
		if (result != null && result.equals(showString + "成功！")) {
			// User.getUser().setLogin_name(user.getLogin_name());
			new AlertDialog.Builder(c)
					.setTitle("提示")
					.setMessage(showString + "成功！")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									((Activity) c).finish();
								}
							}).show();
		} else {
			new AlertDialog.Builder(c).setTitle("提示")
					.setMessage(showString + "失败！")
					.setPositiveButton("确定", null).show();
		}
	}

	// 提示
	public static void showAlert(final Context c, String showString) {
		new AlertDialog.Builder(c).setTitle("提示").setMessage(showString)
				.setPositiveButton("确定", null).show();
	}

	// 计算listview的高
	public static void setListViewHeight(ListView lv) {
		ListAdapter la = lv.getAdapter();
		if (null == la) {
			return;
		}
		// calculate height of all items.
		int h = 0;
		final int cnt = la.getCount();
		for (int i = 0; i < cnt; i++) {
			View item = la.getView(i, null, lv);
			if (item != null) {
				item.measure(0, 0);
				h += item.getMeasuredHeight();
			}
		}
		// reset ListView height

		ViewGroup.LayoutParams lp = lv.getLayoutParams();
		lp.height = h + (lv.getDividerHeight() * (cnt - 1));
		lv.setLayoutParams(lp);
	}

//	// 添加menu菜单选项
//	public static void memuAdd(Menu menu) {
//		menu.add(0, 0, 0, "退出");
//		menu.add(0, 1, 0, "反馈");
//		menu.add(0, 2, 0, "注销用户");
//		menu.add(0, 3, 0, "首页");
//	}
//
//	// menu菜单事件
//	public static void menuOptions(Activity a, MenuItem item) {
//		switch (item.getItemId()) {
//		case 0:
//			Utils.kill(a);
//			break;
//		case 2:
//			// Utils.logout();
//			break;
//		case 3:
//			ActivityFactory.removeAll();
//			break;
//		default:
//			break;
//		}
//	}

//	// 设置标题
//	public static RelativeLayout setHead(String title, Activity a) {
//		RelativeLayout include = (RelativeLayout) a.findViewById(R.id.include1);
//		TextView tv = (TextView) include.findViewById(R.id.tv_title);
//		tv.setText(title);
//		return include;
//	}

	// 设置杠线
	public static void setDelelteLine(TextView tv, String text) {
		SpannableStringBuilder ssb = new SpannableStringBuilder(text);
		ssb.setSpan(new StrikethroughSpan(), 0, ssb.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv.setText(ssb);
	}

	// 字符串是否为空
	public static boolean isEmpty(String s) {
		if (s == null || "".equals(s)) {
			return true;
		}
		return false;
	}

	// 提示
	public static void showAlert(final Activity a, String showString,
			final AlertListener listener) {
		if (a.isFinishing()) {
			return;
		}
		if (listener == null) {
			new AlertDialog.Builder(a).setTitle("提示").setMessage(showString)
					.setPositiveButton("确定", null).show();
		} else {
			new AlertDialog.Builder(a)
					.setTitle("提示")
					.setMessage(showString)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									listener.addAlertListener();
								}
							}).setCancelable(false).show();
		}

	}

	public static ProgressDialog showPd(Activity activity, ProgressDialog pd,
			String text) {
		if (null == pd) {
			pd = new ProgressDialog(activity);
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		}
		pd.setMessage(text);
		if (!activity.isFinishing()) {
			pd.show();
		}
		return pd;
	}

	public static void showIntentAlert(Activity a) {
		showAlert(a, "网络可能存在异常!", null);
	}

	public static void showIntentNull(Activity a) {
		showAlert(a, "没有返回内容!", null);
	}

	public static void simpleJump(Activity a, Class<? extends Activity> clazz) {
		Intent intent = new Intent();
		intent.setClass(a, clazz);
		a.startActivity(intent);
	//	a.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public interface AlertListener {
		void addAlertListener();
	}

	// 将毫秒数换算成x天x时x分x秒x毫秒
	public static String format(long ms) {
		int ss = 1000;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;

		long day = ms / dd;
		long hour = (ms - day * dd) / hh;
		long minute = (ms - day * dd - hour * hh) / mi;
		long second = (ms - day * dd - hour * hh - minute * mi) / ss;
		long milliSecond = ms - day * dd - hour * hh - minute * mi - second
				* ss;

		String strDay = day < 10 ? "0" + day : "" + day;
		String strHour = hour < 10 ? "0" + hour : "" + hour;
		String strMinute = minute < 10 ? "0" + minute : "" + minute;
		String strSecond = second < 10 ? "0" + second : "" + second;
		String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : ""
				+ milliSecond;
		strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : ""
				+ strMilliSecond;
		return strDay + "天" + strHour + "小时" + strMinute + "分钟" + strSecond
				+ "秒";
	}
}
